<template>
  <div class="validate-form">
    <slot></slot>
    <div class="submit-btn" @click.prevent="submitForm">
      <slot name="submit" :item="item">
        <button type="button" class="btn btn-success">提交</button>
      </slot>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue';
import mitt from 'mitt';
type ValidateFunc = () => boolean;
type clearFunc = () => void;
type Events = {
  'form-item-created': ValidateFunc;
  'form-clear-data': clearFunc;
};
export const emitter = mitt<Events>();
export default defineComponent({
  emits: ['form-submit'],
  setup(props, context) {
    let inputFuncArr: ValidateFunc[] = [];
    let clearFuncArr: clearFunc[] = [];
    const item = [1, 2, 3];
    const submitForm = () => {
      const result = inputFuncArr.map(fn => fn()).every(func => func);
      context.emit('form-submit', result);
      if (result) {
        clearFuncArr.forEach(fn => fn());
      }
    };
    const callback = (func?: ValidateFunc): void => {
      if (func) {
        inputFuncArr.push(func);
      }
    };
    const clearDataFunc = (func?: clearFunc): void => {
      if (func) {
        clearFuncArr.push(func);
      }
    };
    emitter.on('form-item-created', callback);
    emitter.on('form-clear-data', clearDataFunc);
    onUnmounted(() => {
      emitter.off('form-item-created', callback);
      emitter.off('form-clear-data', clearDataFunc);
      inputFuncArr = [];
      clearFuncArr = [];
    });
    return { submitForm, item };
  }
});
</script>

<style lang="less">
.validate-form {
  padding: 15px;
  .submit-btn {
    display: inline-block;
  }
}
</style>
